define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'js-md5'], function ($, undefined, Backend, Table, Form, md5) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'auth/admin/index',
                    add_url: 'auth/admin/add',
                    edit_url: 'auth/admin/edit',
                    del_url: 'auth/admin/del',
                    multi_url: 'auth/admin/multi',
                }
            });


            var table = $("#table");

            $(".btn-refresh").hide();

            //在表格内容渲染完成后回调的事件
            table.on('post-body.bs.table', function (e, json) {
                //订单状态链接去掉
                $("td>a.searchit").each(function () {
                    $(this).attr('class', '');
                    $(this).attr('title', '');
                    $(this).attr('data-toggle', '');
                    $(this).attr('data-original-title', '');
                    $(this).css('cursor', 'auto');
                });

                $("tbody tr[data-index]", this).each(function () {
                    if (parseInt($("td:eq(1)", this).text()) == Config.admin.id) {
                        $("input[type=checkbox]", this).prop("disabled", true);
                    }
                });
            });

            var state_arr = {"normal": __('normal'), "hidden": __('hidden')};

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                exportOptions: {
                    ignoreColumn: [0, 'operate'],
                },
                columns: [
                    [
                        {field: 'state', checkbox: true,},
                        {field: 'id', title: 'ID'},
                        {field: 'username', title: __('Username')},
                        {
                            field: 'nickname',
                            title: __('Nickname'),
                            operate: 'LIKE %...%',
                            placeholder: __('Fuzzy_query')
                        },
                        {
                            field: 'groups_text',
                            title: __('Group'),
                            operate: false,
                            formatter: Table.api.formatter.label
                        },
                        {field: 'email', title: __('Email'), operate: 'LIKE %...%', placeholder: __('Fuzzy_query')},
                        {field: 'mobile', title: __('Mobile'), operate: 'LIKE %...%', placeholder: __('Fuzzy_query')},
                        {
                            field: 'status',
                            title: __("Status"),
                            searchList: state_arr,
                            formatter: Table.api.formatter.status
                        },
                        {
                            field: 'logintime',
                            title: __('Login time'),
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            sortable: true
                        },

                        {
                            field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'addtabs',
                                    text: '',
                                    title: '分配局点',
                                    classname: 'btn btn-xs btn-info btn-primary btn-dialog',
                                    icon: 'fa fa-folder-o',
                                    url: 'auth/groupdevice/edit'
                                }],
                            formatter: function (value, row, index) {

                                var that = $.extend({}, this);
                                if (row.id == Config.admin.id) {
                                    $(table).data("operate-addtabs", true);
                                    $(table).data("operate-edit", null);
                                    $(table).data("operate-del", null);
                                } else {
                                    $(table).data("operate-addtabs", true);
                                    $(table).data("operate-edit", true);
                                    $(table).data("operate-del", true);
                                }
                                if (row.id == 1) {
                                    $(table).data("operate-addtabs", null);
                                    $(table).data("operate-edit", null);
                                    $(table).data("operate-del", null);
                                }

                                that.table = table;

                                return Table.api.formatter.operate.call(this, value, row, index);
                            }
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Form.api.bindevent($("form[role=form]"));

            /* 密码加密问题，下个版本再改
            $(".btn-success").click(function(){
                //把password的值换掉，张楠修改
                var form = $("#add-form");
                var form_arr = form.serializeArray();
                var new_form_arr = {};
                for(i=0; i<form_arr.length;i++){
                    if(form_arr[i].name == 'row[password]'){
                        new_form_arr[form_arr[i].name] = md5(form_arr[i].value);
                    }else{
                        new_form_arr[form_arr[i].name] = form_arr[i].value;
                    }
                }
                // console.log(new_form_arr);
                // return false;
                //把password的值换掉

                var str = jQuery.param(new_form_arr);
                //调用Ajax请求方法
                var type = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
                type = type && (type === 'GET' || type === 'POST') ? type : 'GET';
                url = form.attr("action");
                url = url ? url : location.href;
                var params = {};
                var multipleList = $("[name$='[]']", form);
                if (multipleList.size() > 0) {
                    var postFields = form.serializeArray().map(function (obj) {
                        return $(obj).prop("name");
                    });
                    $.each(multipleList, function (i, j) {
                        if (postFields.indexOf($(this).prop("name")) < 0) {
                            params[$(this).prop("name")] = '';
                        }
                    });
                }
                Fast.api.ajax({
                    type: type,
                    url: url,
                    data: str + (Object.keys(params).length > 0 ? '&' + $.param(params) : ''),
                    dataType: 'json',
                    complete: function (xhr, textStatus) {
                        var token = xhr.getResponseHeader('__token__');
                        if (token) {
                            $("input[name='__token__']", form).val(token);
                        }

                        //返回成功跳转，张楠修改
                        var obj = $.parseJSON(xhr.responseText);
                        if(obj.code == 1){
                            console.log(obj)
                            // location.href = "/admin/auth/admin/index"
                            Backend.api.closetabs("/admin/auth/admin");
                            Backend.api.addtabs("/admin/auth/admin.html?ref=addtabs");
                        }
                        //返回成功跳转，张楠修改

                    }

                });
                return false;
            });
            */
        },
        edit: function () {
            Form.api.bindevent($("form[role=form]"));
            /* 密码加密问题，下个版本再改
            $(".btn-success").click(function(){
                //把password的值换掉，张楠修改
                var form = $("#edit-form");
                var form_arr = form.serializeArray();
                var new_form_arr = {};
                for(i=0; i<form_arr.length;i++){
                    if(form_arr[i].name == 'row[password]'){
                        new_form_arr[form_arr[i].name] = md5(form_arr[i].value);
                    }else{
                        new_form_arr[form_arr[i].name] = form_arr[i].value;
                    }
                }
                // console.log(new_form_arr);
                // return false;
                //把password的值换掉

                var str = jQuery.param(new_form_arr);
                //调用Ajax请求方法
                var type = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
                type = type && (type === 'GET' || type === 'POST') ? type : 'GET';
                url = form.attr("action");
                url = url ? url : location.href;
                var params = {};
                var multipleList = $("[name$='[]']", form);
                if (multipleList.size() > 0) {
                    var postFields = form.serializeArray().map(function (obj) {
                        return $(obj).prop("name");
                    });
                    $.each(multipleList, function (i, j) {
                        if (postFields.indexOf($(this).prop("name")) < 0) {
                            params[$(this).prop("name")] = '';
                        }
                    });
                }
                Fast.api.ajax({
                    type: type,
                    url: url,
                    data: str + (Object.keys(params).length > 0 ? '&' + $.param(params) : ''),
                    dataType: 'json',
                    complete: function (xhr, textStatus) {
                        var token = xhr.getResponseHeader('__token__');
                        if (token) {
                            $("input[name='__token__']", form).val(token);
                        }

                        //返回成功跳转，张楠修改
                        var obj = $.parseJSON(xhr.responseText);
                        if(obj.code == 1){
                            console.log(obj)
                            location.href = obj.url
                        }
                        //返回成功跳转，张楠修改

                    }

                });
                return true;
            });
            */
        }
    };
    return Controller;
});